package com.example.spark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.spark.dao.UserDao;
import com.example.spark.entity.Direction;
import com.example.spark.entity.User;
import com.example.spark.entity.result.CommonResult;
import com.example.spark.service.UserService;
import com.example.spark.service.minio.MinioCloudStorageService;
import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

import static com.baomidou.mybatisplus.core.toolkit.IdWorker.getId;


@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private FilesServiceImpl filesService;


    @Resource
    MinioCloudStorageService minIoService;

    /**
     * 查询所有用户加模糊查询加分页
     *
     * @param currentPage 当前页码
     * @param pageSize    条数
     * @return CommonResult
     */
    @Override
    public IPage<User> getAllByPage(Integer currentPage, Integer pageSize, User user) {
        IPage<User> page = new Page(currentPage, pageSize);
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        if (user != null) {
            Long directionId = user.getDirectionId();
            lqw.like(Strings.isNotEmpty(user.getUsername()), User::getUsername, user.getUsername())
                    .like(Strings.isNotEmpty(user.getRealName()), User::getRealName, user.getRealName())
                    .like(Strings.isNotEmpty(user.getGrade()), User::getGrade, user.getGrade())
                    .in(user.getIsMapper() != null, User::getIsMapper, user.getIsMapper())
                    .eq(User::getIsAdmin, 0)
                    .eq(directionId != null, User::getDirectionId, directionId);
        }else {
            lqw=null;
            Long directionId = null;
        }
        IPage<User> userPage = userDao.selectPage(page, lqw);
        userPage.getRecords().forEach(user1 -> {
            Direction direction = userDao.checkDirec(user1.getDirectionId());
            if (direction == null){
                user1.setDirection(null);
                user1.setDirectionPhoto(null);
            }else {
                user1.setDirection(direction.getLearningDirection());
                user1.setDirectionPhoto(direction.getPhoto());
            }
        });
        return userPage;


    }






    /**
     * 通过id删除用户
     *
     * @param id 用户id
     * @return CommonResult
     */
    @Override
    public CommonResult deleteById(Long id) {
        User user = userDao.selectById(id);
        if (user != null) {
            if (user.getIsAdmin() == 0) {
                LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(User::getDelFlag, 0).eq(User::getId, id);
                userDao.delete(queryWrapper);
                filesService.deleteByUserId(id);
                return new CommonResult<>(200, "success");
            } else {
                return new CommonResult<>(200, "不能删除管理员");
            }
        }

        return new CommonResult<>(200, "用户不存在");
    }


    /**
     * 添加用户
     *
     * @param user 用户
     * @return CommonResult
     */
    @Override
    public CommonResult add(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        User user2 = userDao.selectOne(queryWrapper);
        //判断用户名,电话，邮箱，博客地址，照片地址是否唯一
        if (user2 == null) {
            queryWrapper.eq(User::getPhone, user.getPhone());
            User user3 = userDao.selectOne(queryWrapper);
            if (user3 == null) {
                queryWrapper.eq(User::getEmail, user.getEmail());
                User user4 = userDao.selectOne(queryWrapper);
                if (user4 == null) {
                    queryWrapper.eq(User::getBlog, user.getBlog());
                    User user5 = userDao.selectOne(queryWrapper);
                    if (user5 == null) {
                        queryWrapper.eq(User::getPhoto, user.getPhoto());
                        User user6 = userDao.selectOne(queryWrapper);
                        if (user6 == null) {
                            user.setId(getId());
                            user.setPhoto(String.valueOf(getId()));
                            userDao.insert(user);
                            return new CommonResult<>(200, "success");
                        }
                        return new CommonResult<>(200, "图片地址已存在");
                    }
                    return new CommonResult<>(200, "博客地址已存在");
                }
                return new CommonResult<>(200, "邮箱已存在");
            }
            return new CommonResult<>(200, "电话号码已存在");
        }
        return new CommonResult<>(200, "用户已存在");
    }

    /**
     * 修改用户信息
     *
     * @param user 用户
     * @return CommonResult
     */
    @Override
    public CommonResult<User> update(User user) {

        User user1 = userDao.selectById(user.getId());
        if (user1.getIsAdmin() == 1) {
            return new CommonResult<>(200, "不能修改管理员");
        }
        //判断被修改的用户是否存在
        if (user1 != null) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, user.getUsername()).ne(User::getId,user.getId());
            User user2 = userDao.selectOne(queryWrapper);
            //判断用户名,电话，邮箱，博客地址，照片地址是否唯一
            if (user2 == null) {
                queryWrapper.eq(User::getPhone, user.getPhone());
                User user3 = userDao.selectOne(queryWrapper);
                if (user3 == null) {
                    queryWrapper.eq(User::getEmail, user.getEmail());
                    User user4 = userDao.selectOne(queryWrapper);
                    if (user4 == null) {
                        queryWrapper.eq(User::getBlog, user.getBlog());
                        User user5 = userDao.selectOne(queryWrapper);
                        if (user5 == null) {
                            queryWrapper.eq(User::getPhoto, user.getPhoto());
                            User user6 = userDao.selectOne(queryWrapper);
                            if (user6 == null) {
                                user.setIsAdmin(0);
                                userDao.updateById(user);
                                return new CommonResult<>(200, "success");
                            }
                            return new CommonResult<>(200, "图片地址已存在");
                        }
                        return new CommonResult<>(200, "博客地址已存在");
                    }
                    return new CommonResult<>(200, "邮箱已存在");
                }
                return new CommonResult<>(200, "电话号码已存在");
            }
            return new CommonResult<>(200, "用户名已存在");
        }
        return new CommonResult<>(200, "用户不存在");
    }

    @Override
    public Direction checkDirec(Long directionId) {
        Direction direction = userDao.checkDirec(directionId);
        System.err.println(direction);
        return direction;
    }

    /**
     * 添加/修改用户图片
     *
     * @param file 图片文件
     * @param id   用户id
     * @return CommonResult
     * @throws IOException
     */
    @Override
    public CommonResult addPicture(MultipartFile file, Long id) throws IOException {
        User user = userDao.selectById(id);
        if (user == null) {
            return new CommonResult<>(200, "用户不存在");
        }
        // getOriginalFileName方法获取的是文件的完整名称，包括文件名称+文件拓展名
        //后缀
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        // 上传文件并获取文件存储路径
        String url = minIoService.uploadPhotoSuffix(file.getBytes(), extension, user.getRealName());
        user.setPhoto(url);
        userDao.updateById(user);
        return new CommonResult<>(200, "success");
    }




}
